package com.superyee.commonlib.http;

import android.text.TextUtils;

import com.superyee.commonlib.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by guoguo on 2017/11/16.
 */

public class HttpParams {


    private List<OkHttpClientManager.Param> params;
    private List<String> fileKey;
    private List<File> files;

    public HttpParams() {
        params = new ArrayList<>();
        fileKey = new ArrayList<>();
        files = new ArrayList<>();
    }

    public void addParam(String key, String value) {
        if (!TextUtils.isEmpty(key)) {
            params.add(new OkHttpClientManager.Param(key, value == null ? "" : value));
        }
    }

    /**
     * key和value都不能为空,为空将忽略
     *
     * @param key
     * @param value
     */
    public void addParamNotNull(String key, String value) {
        if (!StringUtil.isEmpty(key) && !StringUtil.isEmpty(value)) {
            params.add(new OkHttpClientManager.Param(key, value));
        }
    }

    public void addFile(String key, File file) {
        if (file != null) {
            fileKey.add(key);
            files.add(file);
        }
    }

    public void addFile(String key, String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        if (file != null && file.exists()) {
            fileKey.add(key);
            files.add(file);
        }
    }

    public List<OkHttpClientManager.Param> getParams() {
        return params;
    }

    public List<File> getFiles() {
        return files;
    }

    public List<String> getFileKey() {
        return fileKey;
    }

    public void clear() {
        params.clear();
        fileKey.clear();
        files.clear();
    }

    /**
     * 描述：转换为参数字符串.
     *
     * @return the string
     */
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (OkHttpClientManager.Param entry : params) {
            if (result.length() > 0)
                result.append("&");

            result.append(entry.key);
            result.append("=");
            result.append(entry.value);
        }
        return result.toString();
    }

    public String getParamString() {
        StringBuffer sb = new StringBuffer();
        for (OkHttpClientManager.Param entry : params) {
            sb.append(entry.key + "=" + entry.value);
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.lastIndexOf("&"));
        }
        return s;
    }


}
